package org.xxx.epms.result.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.xxx.epms.result.mapper.AqiGradeMapper;
import org.xxx.epms.result.models.AqiGrade;
import org.xxx.epms.result.service.AqiGradeService;

import java.util.List;

@Service
public class AqiGradeServiceImpl extends ServiceImpl<AqiGradeMapper, AqiGrade> implements AqiGradeService {

    @Autowired
    private AqiGradeMapper aqiGradeMapper;

    @Override
    public AqiGrade getAqiGradeByLevel(Integer level) {
        QueryWrapper<AqiGrade> wrapper = new QueryWrapper<>();
        wrapper.eq("aqi_level", level);
        return aqiGradeMapper.selectOne(wrapper);
    }

    @Override
    public List<AqiGrade> listAqiGrades() {
        QueryWrapper<AqiGrade> wrapper = new QueryWrapper<>();
        wrapper.orderByAsc("aqi_level");
        return aqiGradeMapper.selectList(wrapper);
    }

    @Override
    public Integer getAqiGradeByCoValue(Integer coValue) {
        if(coValue < 0){
            return 0;
        }
        QueryWrapper<AqiGrade> queryWrapper = new QueryWrapper<>();
        queryWrapper.apply("aqi_co_min <= {0} AND aqi_co_max >= {0}", coValue);
        queryWrapper.orderByAsc("aqi_level");
        queryWrapper.last("LIMIT 1");
        AqiGrade aqiGrade = aqiGradeMapper.selectOne(queryWrapper);
        if (aqiGrade != null) {
            return aqiGrade.getAqiLevel();
        } else {
            // co 值大于最大等级的最大值，将其设为最大等级
            return 6; // 假设最大等级为 6
        }
    }

    @Override
    public Integer getAqiGradeBySo2Value(Integer so2Value) {
        if(so2Value < 0){
            return 0;
        }
        QueryWrapper<AqiGrade> queryWrapper = new QueryWrapper<>();
        queryWrapper.apply("aqi_so2_min <= {0} AND aqi_so2_max >= {0}", so2Value);
        queryWrapper.orderByAsc("aqi_level");
        queryWrapper.last("LIMIT 1");
        AqiGrade aqiGrade = aqiGradeMapper.selectOne(queryWrapper);
        if (aqiGrade != null ) {
           return aqiGrade.getAqiLevel();
        }else{
            return 6; // 假设最大等级为 6
        }
    }

    @Override
    public Integer getAqiGradeByPmValue(Integer pmValue) {
        if(pmValue < 0){
            return 0;
        }
        QueryWrapper<AqiGrade> queryWrapper = new QueryWrapper<>();
        queryWrapper.apply("aqi_pm_min <= {0} AND aqi_pm_max >= {0}", pmValue);
        queryWrapper.orderByAsc("aqi_level");
        queryWrapper.last("LIMIT 1");
        AqiGrade aqiGrade = aqiGradeMapper.selectOne(queryWrapper);
        if (aqiGrade != null ) {
            return aqiGrade.getAqiLevel();
        }else{
            return 6; // 假设最大等级为 6
        }
    }
}
